package com.exm.mqttservice;

import com.exm.service.DataService;
import com.exm.service.EmailService;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 订阅端
 */
@Component
public class MqttSubsribe {
    private static final String USERNAME = "root"; // 设置用户名
    private static final String PASSWORD = "2583549902@qq.com"; // 设置密码
    private static final String BROKER = "tcp://47.98.117.180:1883";
    private static final String TOPIC = "sensor/data";


    public MqttClient mqttClient;

    @Autowired
    DataService dataService;

    @Autowired
    EmailService emailService;
    public MqttSubsribe() throws Exception {
        // 创建 MQTT 客户端
        this.mqttClient = new MqttClient(BROKER, MqttClient.generateClientId());

        // 设置连接选项
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(USERNAME); // 设置用户名
        options.setPassword(PASSWORD.toCharArray()); // 设置密码

        // 连接到 MQTT Broker
        mqttClient.connect(options);
    }



    @Scheduled(fixedRate = 5000) // 每秒发送一次数据
    public void subscribe() {

        try {
            mqttClient.subscribe(TOPIC, (topic, message) -> {
                String payload = new String(message.getPayload());
                float dataValue = Float.parseFloat(payload.substring(payload.indexOf(":") + 1, payload.indexOf("}")));
                System.out.println(dataValue);
//                 存储到数据库
                dataService.saveData(dataValue);

                // 检查阈值并发送邮件
                if (dataValue > 0.9) {
                    emailService.simple("2583549902@qq.com","Threshold Alert", "Data value exceeded threshold: " + dataValue);
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


}

